package com.hwd.gmall.web.controller;

import com.hwd.gmall.list.feign.SearchFeignClient;
import com.hwd.gmall.web.util.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Map;

/**
 * 前端搜索页面的控制层
 *
 * @author 黄伟东/Victor
 * @date 2022/4/29 14:09
 */
@Controller
@RequestMapping(value = "/web/search")
public class SearchController {

    @Qualifier("com.hwd.gmall.list.feign.SearchFeignClient")
    @Autowired
    private SearchFeignClient searchFeignClient;

    @Value("${item.url}")
    private String itemUrl;

    /**
     * 打开搜索页面
     *
     * @param model      数据模型
     * @param searchData 搜索条件
     * @return java.lang.String
     */
    @GetMapping
    public String search(Model model,
                         @RequestParam Map<String, String> searchData) {
        // 远程调用搜索接口获取搜索数据
        Map<String, Object> result = searchFeignClient.search(searchData);

        // 把搜索结果数据放到model中
        model.addAllAttributes(result);

        // 把搜索条件放到model中，用于前端页面回显
        model.addAttribute("searchData", searchData);

        // 获取当前的url
        model.addAttribute("url", getUrl(searchData));

        // 获取分页对象
        model.addAttribute("pageInfo", getPageInfo(searchData, result));

        // 获取商品详情页的前缀
        model.addAttribute("itemUrl", itemUrl);

        return "list";
    }

    /**
     * 获取分页对象
     *
     * @param searchData 搜索条件
     * @param result     搜索数据
     * @return com.hwd.gmall.web.util.Page<java.lang.Object>
     */
    private Page<Object> getPageInfo(Map<String, String> searchData, Map<String, Object> result) {
        // 获取总命中的数量
        Object totalHits = result.get("totalHits");
        // 每页显示的数量
        int size = 5;
        // 当前的页码
        Integer page = getPage(searchData.get("page"));
        // 构建一个分页对象
        Page<Object> pageInfo = new Page<>(Long.parseLong(totalHits.toString()), page, size);
        return pageInfo;
    }

    /**
     * 根据搜索条件获取当前的url
     *
     * @param searchData 搜索条件
     * @return java.lang.String
     */
    private String getUrl(Map<String, String> searchData) {
        // 初始化url
        StringBuilder url = new StringBuilder("/web/search?");
        // /web/search?keywords=手机&tradeMark=华为
        searchData.entrySet().stream()
                .filter(entry -> !("sortField".equals(entry.getKey()) ||
                        "sortRule".equals(entry.getKey()) || "page".equals(entry.getKey())))
                .forEach(entry -> url.append(entry.getKey()).append("=").append(entry.getValue()).append("&"));
        System.out.println(url.substring(0, url.length() - 1));
        return url.substring(0, url.length() - 1);
    }

    /**
     * 获取用户传入的页码
     *
     * @param page 页码
     * @return java.lang.Integer
     */
    private Integer getPage(String page) {
        try {
            int i = Integer.parseInt(page);
            return i > 0 ? i : 1;
        } catch (NumberFormatException e) {
            return 1;
        }
    }
}
